package net.cz.wc.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UtilDate {
	
	/**
	 * Creates a list of intervals between the start and end date, each interval has 
	 * a sizeInSeconds length 
	 * @param start
	 * @param end
	 * @param sizeInSeconds
	 * @return null if there are no intervals to be generated, for example when start date
	 * is greater than end date.
	 * If start and end date are equals it only generates one interval which start and end date
	 * are the same.
	 */
	public static List<DateInterval> createIntervals(Date start, Date end, long sizeInSeconds) {
		
		if (start == null || end == null || start.compareTo(end) > 0) {
			return null;
		}
		
		// the minimum number of intervals is 1, it only happens when start and end date are the same
		// or when its difference is less than sizeInSeconds
		int numberOfIntervals = (int)((end.getTime() - start.getTime()) / (1000 * sizeInSeconds)) + 1;
		
		List<DateInterval> intervals = new ArrayList<DateInterval>();
		Date intStart = start;
		Date intEnd = end;
		
		if (numberOfIntervals > 0) {
			for (int i = 0; i < numberOfIntervals; i++) {
				intEnd = new Date(intStart.getTime() + (sizeInSeconds - 1) * 1000);
				DateInterval inter = null;
				if (intEnd.compareTo(end) <= 0) {
					inter = new DateInterval(intStart, intEnd);
					
					// next interval starts in the next second
					intStart = new Date(intEnd.getTime() + 1000);
				} else {
					inter = new DateInterval(intStart, end);
				}
				
				intervals.add(inter);
			}
		}
		
		return intervals;
	}
}
